<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\Sku as SkuService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterial as OrderMaterialService;

class Stat extends Admin
{

    public function initialize() {
    	parent::initialize();
    }

    /**
     * 交货趋势分析
     *
     * @author KING
     * @date 2020年7月7日
     *
     * @return \think\response\Json|string
     */
    public function shipment()
    {
    	$factoryKV = [0 => '未分配'] + getFactoryKV(true);

    	$days = [];
    	for($i = 0; $i < 12; $i++) {
    		$dayStart = strtotime("+{$i} day 00:00:00");
    		$days[$i] = date("m月d日", $dayStart);
    	}

    	$dayStart = strtotime("+0 day 00:00:00");
    	$dayEnd = strtotime("+11 day 23:59:59");

    	$where[] = ['status', 'in', [0, 1]];
    	$where[] = ['shipment_time', 'between', [$dayStart, $dayEnd]];
    	$list = db('order')->where($where)->field('id,factory_id,shipment_time,quantity')->select();

    	$statItem = [];
    	$statTotal = [];
    	foreach ($list as $k => $v) {
    		$factoryId = $v['factory_id'];
    		$date = date('Ymd', $v['shipment_time']);
    		$quantity = $v['quantity'];

    		if (isset($statItem[$factoryId][$date])) $statItem[$factoryId][$date] += $quantity;
    		else $statItem[$factoryId][$date] = $quantity;

    		if (isset($statTotal[$date])) $statTotal[$date] += $quantity;
    		else $statTotal[$date] = $quantity;
    	}

    	$stat = [];
    	foreach ($statItem as $factoryId => $item) {
    		for($i = 0; $i < 12; $i++) {
    			$date = date('Ymd', strtotime("+{$i} day 00:00:00"));
    			if (!array_key_exists($date, $item)) $item[$date] = 0;
    		}

    		ksort($item);

    		$stat[] = [
    			'name' => arrayGet($factoryKV, $factoryId, ''),
    			'data' => array_values($item),
    		];
    	}

    	for($i = 0; $i < 12; $i++) {
    		$date = date('Ymd', strtotime("+{$i} day 00:00:00"));
    		if (!array_key_exists($date, $statTotal)) $statTotal[$date] = 0;
    	}
    	ksort($statTotal);

    	$statAll[] = [
    		'name' => '汇总',
    		'data' => array_values($statTotal),
    	];

    	$data = ['days' => $days, 'stat' => $stat, 'statAll' => $statAll];
    	$assign = ['data' => json_encode($data), 'factoryKV' => $factoryKV];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 订单跟踪报表
     */
    public function orderTrack(){
        $factoryKV = getFactoryKV(false);
        $factoryOutgoKV = getFactoryOutgoKV(null);
        $systemUserKV = getSystemUserKV(null);
        $groupKV = getGroupKV(0);
        $export     = $this->request->param('export/d', 0);
        if ($this->request->isAjax() || $export>0) {
            $where      = $data = [];
            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $factorId      = $this->request->param('factory_id/d', 0);
            $orderStatus    = $this->request->param('order_status/s');
            $clientOrdernum    = $this->request->param('client_ordernum/s');
            $sku    = $this->request->param('sku/s');
            $createDateRange    = $this->request->param('create_date_range/s');
            $overDateRange    = $this->request->param('over_date_range/s');
            $caichuangOverDateRange    = $this->request->param('caichuang_over_date_range/s');

            $where[] = ['a.id','>',0];
            if (FACTORY_IDS != '*') {
                $where[] = ['factory_id', 'in', FACTORY_IDS];
            }
            if ($factorId) {
                $where[] = ['factory_id', '=', $factorId];
            }

            if ($orderStatus != '') {
                switch ($orderStatus){
                    case 1:
                        $where[] = ['caigou_status', '=', 0];
                        break;
                    case 2:
                        $where[] = ['caigou_status', '=', 1];
                        $where[] = ['caichuang_status', '=', 0];
                        break;
                    case 3:
                        $where[] = ['caichuang_status', '=', 1];
                        $where[] = ['chejian_status', '=', 0];
                        break;
                    case 4:
                        $where[] = ['chejian_status', '=', 1];
                        $where[] = ['tail_status', '=', 0];
                        break;
                    case 5:
                        $where[] = ['tail_status', '=', 1];
                        $where[] = ['real_shipment_status', '=', 0];
                        break;
                    case 6:
                        $where[] = ['real_shipment_status', '=', 1];
                        $where[] = ['status', '=', 1];
                        break;
                    case 7:
                        $where[] = ['status', '=', 2];
                        break;
                }
            }
            if ($clientOrdernum != '') {
                $where[] = ['a.client_ordernum', '=', $clientOrdernum];
            }
            switch (env('env_site')) {
                case 'riwei':
                    $ext_id = trim($this->request->param('ext_id'));
                    $ext_id != '' && $where[] = ['a.ext_id', 'like', $ext_id];
                    break;
            }
            if ($sku != '') {
                $where[] = ['sku', 'like', "%".$sku."%"];
            }
            if ($createDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
                $where[] = ['a.create_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($overDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $overDateRange));
                $where[] = ['over_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($caichuangOverDateRange != '') {
                list($startTime, $endTime) = array_map('strtotime', explode('~', $caichuangOverDateRange));
                $where[] = ['caichuang_over_time', 'between', [$startTime, $endTime+86399]];
            }
            if ($export) {
                set_time_limit(0);
                ini_set('memory_limit', '1024M');
                $page = 1;
                $limit = 99999;
                $data['count'] = db('order a')->where($where)->count('id');
                if($data['count']>20000){//
                    echo "<script language='JavaScript'>alert('当前导出数据过大已超过2万条，请筛选后再选择导出');window.close()</script>";die;
                }
            }
            $order = "a.create_time desc";
            $orderList = db('order a')->join('order_ext ext', 'a.id = ext.order_id','left')
                ->field("a.*,a.client_ordernum as client_ordernum,ext.material_cost_discuss_add,ext.mes_factory,ext.material_cost_little,ext.material_cost_total,ext.cost_profit,ext.cost,
                ext.price,ext.accounting_diff_remark,dress_cost_total,dress_process_names,dress_process_counts,dress_process_unitprices,dress_process_prices,
                special_process_a_name,special_process_b_name,special_process_c_name,special_process_d_name,special_process_e_name,special_process_a_unitprice,special_process_b_unitprice,special_process_c_unitprice,special_process_d_unitprice,special_process_e_unitprice,accounting_diff_remark")
                ->where($where)->page($page)->limit($limit)->orderRaw($order)->select();
            //echo lastsql();die;
            $skuService = new SkuService();
            $orderSizeService = new OrderSizeService();
            $orderMaterialService = new OrderMaterialService();
            $orderIds=array_column($orderList,'id');
            $materialCostRet=db('order_material')->where('order_id', 'in', $orderIds)->field('sum(custom_simple_cost) as custom_simple_cost,order_id,client_ordernum')
                ->group("order_id")->select();
            $customMaterialCostList=array_column($materialCostRet,'custom_simple_cost','order_id');

            foreach ($orderList as $k => $v) {
                $osList = $orderSizeService->getListByOrderId($v['id'], 'mid,order_count,daohuo_count,shicai_count,jiaohuo_tail_count,delivery_count,jiaohuo_count,size_name,tail_stock_in_out,tail_defective');
                $orderList[$k]['osList'] = $osList;
                $orderList[$k]['osJson'] = json_encode($osList);
                $orderList[$k]['groupKV'] = [0 => '请选择'] + getGroupKV($v['factory_id']);
                $orderList[$k]['osStat'] = ['order_count' => array_sum(array_column($osList, 'order_count')), 'shicai_count' => array_sum(array_column($osList, 'shicai_count')), 'jiaohuo_count' => array_sum(array_column($osList, 'jiaohuo_count')), 'jiaohuo_tail_count' => array_sum(array_column($osList, 'jiaohuo_tail_count')), 'delivery_count' => array_sum(array_column($osList, 'delivery_count')), 'daohuo_count' => array_sum(array_column($osList, 'daohuo_count'))];
                $orderList[$k]['shipment_time_diff'] = $v['status'] == 2 ? formatSecond($v['shipment_time'] - $v['over_time']) : formatSecond($v['shipment_time'] - time());
                $orderList[$k]['create_time_diff'] = $v['status'] == 2 ? formatSecond($v['over_time'] - $v['shipment_time']) : formatSecond(time() - $v['shipment_time']);
                $orderList[$k]['o_type_text'] = arrayGet(config('mimo.order_otype'), $v['o_type'], '');
                $orderList[$k]['delete_text'] = $v['status'] == 99 ? '已废除' : '';
                $orderList[$k]['sInfo'] = $skuService->getInfoBySku($v['sku']);
                $orderList[$k]['fob_price']= $v['price'];
                $orderList[$k]['sku_price']=$orderList[$k]['sInfo']['price'];
                $orderList[$k]['processing_charges']= $orderList[$k]['sInfo']['cost'];
                $orderList[$k]['sewing_charges']= round($orderList[$k]['sInfo']['chewei_price']+$orderList[$k]['sInfo']['sixian_price']+$orderList[$k]['sInfo']['zhuanji_price'],2);//工厂针车位工价
                $orderList[$k]['custom_material_cost']=isset($customMaterialCostList[$v['id']])?$customMaterialCostList[$v['id']]:0.00; //mes面辅单项价格
                $orderList[$k]['custom_material_total']=round(($v['material_cost_discuss_add']+$orderList[$k]['custom_material_cost'])*$orderList[$k]['osStat']['shicai_count'],2);//MES面辅总价
                $orderList[$k]['special_process_amounts']=0;
                $special_process_name_str=$orderList[$k]['special_process_a_name'];
                $special_process_name_str.=empty($orderList[$k]['special_process_b_name']) ? '' : "/".$orderList[$k]['special_process_b_name'];
                $special_process_name_str.=empty($orderList[$k]['special_process_c_name']) ? '' : "/".$orderList[$k]['special_process_c_name'];
                $special_process_name_str.=empty($orderList[$k]['special_process_d_name']) ? '' : "/".$orderList[$k]['special_process_d_name'];
                $special_process_name_str.=empty($orderList[$k]['special_process_e_name']) ? '' : "/".$orderList[$k]['special_process_e_name'];//二次工艺名称
                $specialProcessPriceStr=$orderList[$k]['special_process_a_unitprice'];
                $specialProcessPriceStr.=empty($orderList[$k]['special_process_b_unitprice']) || $orderList[$k]['special_process_b_unitprice']==0.00 ? '' : "/".$orderList[$k]['special_process_b_unitprice'];
                $specialProcessPriceStr.=empty($orderList[$k]['special_process_c_unitprice']) || $orderList[$k]['special_process_c_unitprice']==0.00 ? '' : "/".$orderList[$k]['special_process_c_unitprice'];
                $specialProcessPriceStr.=empty($orderList[$k]['special_process_d_unitprice']) || $orderList[$k]['special_process_d_unitprice']==0.00 ? '' : "/".$orderList[$k]['special_process_d_unitprice'];
                $specialProcessPriceStr.=empty($orderList[$k]['special_process_e_unitprice']) || $orderList[$k]['special_process_e_unitprice']==0.00 ? '' : "/".$orderList[$k]['special_process_e_unitprice'];
                $orderList[$k]['mes_process_price']=$specialProcessPriceStr;
                $orderList[$k]['MES_sweing_total']=round($orderList[$k]['sInfo']['cost']*$orderList[$k]['osStat']['jiaohuo_count'],2); //mes针车金额
                $orderList[$k]['factory_sweing_total']=round($orderList[$k]['sewing_charges']*$orderList[$k]['osStat']['jiaohuo_count'],2);
                $orderList[$k]['factory_shipment_amounts']=round($orderList[$k]['fob_price']*$orderList[$k]['osStat']['daohuo_count'],2);
                $orderList[$k]['store_checkin_amounts']=round($orderList[$k]['fob_price']*$orderList[$k]['store_count'],2);
                $orderList[$k]['special_process_name_str']=$special_process_name_str;
                $orderList[$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
                $orderList[$k]['group_name'] = arrayGet($groupKV, $v['group_id'], '');
                $orderList[$k]['factory_outgo_name'] = arrayGet($factoryOutgoKV, $v['factory_outgo_id'], '');
                $orderList[$k]['caichuang_user_name'] = arrayGet($systemUserKV, $v['caichuang_user_id'], '');
                $orderList[$k]['caigou_user_name'] = arrayGet($systemUserKV, $v['caigou_user_id'], '');
            }
            if ($export) {
                $this->orderTrackExpXls('订单跟踪报表-' .date('YmdHi'), $orderList);
                exit;
            }
            $data['data']=$orderList;
            $data['clientStatus']=config('mimo.client_status');
            $data['count'] = db('order as a')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }

        $assign = [
            'orderFrom' => [0 => ''] + config('mimo.order_from'),
            'clientStatus' => config('mimo.client_status'),
            'factoryKV' => [0 => '请选择'] + $factoryKV,
            'groupKV' => $groupKV,
            'factoryOutgoKV' => $factoryOutgoKV,
        ];
        return $this->assign($assign)->fetch();
    }

    private function orderTrackExpXls($fileName, &$data) {
        $head = ['裁剪日期','订单号','SKU','分配工厂','MES工厂','下单时间','订单数','生产状态','MES面辅单价','MES物料费','MES物料费(含利润)','MES加工费含倍率','MES加工费(含利润)','MES单件总计','核价增加','实际面辅料单价','MES面辅总金额'
            ,'采购总金额','面辅赢亏情况','实裁数','裁剪员','异常备注','组别','车间数','MES加工费(含倍)','工厂针车位工价','MES车位金额','下车位金额','出货数','出货日期','MES入仓日期','MES入仓数','MES FOB价','出货金额','入仓金额'
            ,'成衣二次工艺名称','成衣二次工艺单价','成衣二次工艺净用量'
            ,'二次工艺A名称','二次工艺A单价','二次工艺B名称','二次工艺B单价','二次工艺C名称','二次工艺C单价','二次工艺D名称','二次工艺D单价','field'];
        $params = [];
        $clientStatus=config('mimo.client_status');
        $exportdata = [];
        foreach ($data as $k => $v) {
            $exportdata[] = [
                $v['caichuang_over_time']==0 ? '':date('Y-m-d', $v['caichuang_over_time']),
                $v['client_ordernum'],
                $v['sku'],
                $v['factory_name'],
                $v['mes_factory'],
                $v['create_time']==0 ? '':date('Y-m-d', $v['create_time']),
                $v['osStat']['order_count'],
                $clientStatus[$v['client_status']],
                $v['custom_material_cost'],
                $v['material_cost_little'],
                $v['material_cost_total'],
                $v['cost'], //MES加工费含倍率
                $v['cost_profit'],
                $v['price'],
                $v['material_cost_discuss_add'],
                $v['osStat']['shicai_count']>0 ? round($v['caigou_total_money']/$v['osStat']['shicai_count'],2) : 0, //实际面辅料单价
                $v['custom_material_total'],
                $v['caigou_total_money'],
                $v['custom_material_total']-$v['caigou_total_money'],
                $v['osStat']['shicai_count'],
                $v['caichuang_user_name'],
                $v['accounting_diff_remark'],
                $v['group_name'],
                $v['osStat']['jiaohuo_count'],
                $v['processing_charges'],
                $v['sewing_charges'],
                $v['MES_sweing_total'],
                $v['factory_sweing_total'],
                $v['osStat']['daohuo_count'],
                $v['tail_over_time']==0 ? '':date('Y-m-d', $v['tail_over_time']),
                $v['store_time']==0 ? '':date('Y-m-d', $v['store_time']),
                $v['store_count'],
                $v['fob_price'],
                $v['factory_shipment_amounts'],
                $v['store_checkin_amounts'],
                $v['dress_process_names'],
                $v['dress_process_unitprices'],
                $v['dress_process_counts'],
                $v['special_process_a_name'],
                $v['special_process_a_unitprice'],
                $v['special_process_b_name'],
                $v['special_process_b_unitprice'],
                $v['special_process_c_name'],
                $v['special_process_c_unitprice'],
                $v['special_process_d_name'],
                $v['special_process_d_unitprice'],
            ];
        }
        $params['file'] = $fileName;
        $params['sheet'] = [
            [
                'head' => $head, // 表头
                'data' => $exportdata,
            ],
        ];
        unset($data);
        plugins_run('excel/excel/export', $params);
    }

}